package com.irun.ibuffet.application;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.app.Application;

/***
 * @author huangsm
 * @date 2012-9-1
 * @email huangsanm@gmail.com
 * @desc application
 */
public class IBuffetApplication extends Application {

	/**
	 * 处理时间长的线程池的线程最少保持数
	 */
	public final static int SLOW_THREAD_MIN = 1;

	/**
	 * 处理时间长的线程池的线程最多保持数
	 */
	public final static int SLOW_THREAD_MAX = 5;

	/**
	 * 处理时间短的线程池的线程最少保持数
	 */
	public final static int FAST_THREAD_MIN = 3;

	/**
	 * 处理时间短的线程池的线程最多保持数
	 */
	public final static int FAST_THREAD_MAX = 5;

	/**
	 * 线程空闲时间
	 */
	public final static int THREAD_POOL_TIMEOUT = 60;

	/**
	 * 处理时间长的线程池
	 */
	private ThreadPoolExecutor slowThreadPool;

	/**
	 * 处理时间短的线程池
	 */
	private ThreadPoolExecutor fastThreadPool;




	/**
	 * 获取处理时间快的线程池
	 * 
	 * @return the fastThreadPool
	 */
	public ThreadPoolExecutor getFastThreadPool() {
		return fastThreadPool;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		initThreadPool();
	}

	/**
	 * 初始化线程池
	 */
	private void initThreadPool() {
		/**
		 * 创建调用处理逻辑事务需要较长时间的线程池
		 */
		slowThreadPool = new ThreadPoolExecutor(SLOW_THREAD_MIN,
				SLOW_THREAD_MAX, THREAD_POOL_TIMEOUT, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>(),
				new ThreadPoolExecutor.DiscardOldestPolicy());

		/**
		 * 创建调用处理逻辑事务相对较快的线程池
		 */
		fastThreadPool = new ThreadPoolExecutor(FAST_THREAD_MIN,
				FAST_THREAD_MAX, THREAD_POOL_TIMEOUT, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>(),
				new ThreadPoolExecutor.DiscardOldestPolicy());
	}


	/**
	 * 添加到处理时间长的线程池执行任务
	 * 
	 * @param runnable
	 */
	public void addTaskToSlowThreadPool(Runnable runnable) {
		if (runnable != null)
			slowThreadPool.execute(runnable);
	}

	/**
	 * 获取处理时间慢的线程池
	 * 
	 * @return the slowThreadPool
	 */
	public ThreadPoolExecutor getSlowThreadPool() {
		return slowThreadPool;
	}

	/**
	 * 添加到处理时间快的线程池执行任务
	 * 
	 * @param runnable
	 */
	public void addTaskToFastThreadPool(Runnable runnable) {
		if (runnable != null)
			fastThreadPool.execute(runnable);
	}
}
